package com.bckj.freshnow.order.trade.execution.create;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.bckj.fastboot.core.execution.Execution;
import com.bckj.fastboot.core.execution.ExecutionContext;
import com.bckj.fastboot.core.redis.RedisOps;
import com.bckj.freshnow.common.constant.TradeOrderCacheConstants;
import com.bckj.freshnow.order.model.CreateTradeOrderRequest;
import com.bckj.freshnow.order.model.TradeOrderTempDTO;
import com.bckj.freshnow.order.trade.fsm.TradeOrderContext;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * 创建交易订单暂存管理
 */
@Component
@RequiredArgsConstructor
public class CreateTradeOrderTempExecution implements Execution {

    private final RedisOps redisOps;

    @Override
    public void execute(ExecutionContext context) {
        TradeOrderContext ctx = (TradeOrderContext) context;
        CreateTradeOrderRequest request = (CreateTradeOrderRequest) ctx.getRequest();
        String tempId = request.getParentOrderNo();
        if (StrUtil.isNotBlank(tempId)) {
            //tempId不为空 说明是要获取使用暂存信息
            TradeOrderTempDTO temp = (TradeOrderTempDTO) redisOps.get(TradeOrderCacheConstants.TRADE_ORDER_TEMP + request.getParentOrderNo());
            Assert.notNull(temp, "订单信息不存在，请重新下单");
            ctx.setParentOrder(temp.getParentOrder());
        } else {
            //tempId为空 说明是要暂存交易信息
            tempId = ctx.getParentOrder().getParentOrderNo();
            String key = TradeOrderCacheConstants.TRADE_ORDER_TEMP + tempId;
            redisOps.set(key,
                    TradeOrderTempDTO.create()
                            .setParentOrder(ctx.getParentOrder()), 3600);
            ctx.setParentOrderNo(tempId);
        }
    }
}
